"""
内存监控客户端
功能：采集内存使用数据并通过API提交到服务端
"""
import psutil
import requests
from datetime import datetime

# 配置项
API_URL = "http://192.168.88.1:8000/v1/mem"  # 替换为实际服务端地址
TIMEOUT = 20  # 请求超时时间(秒)
UNITS = "MB"  # 数据单位(MB/GB)

def get_hostname():
    """获取主机名"""
    try:
        return psutil.users()[0].name if psutil.users() else "unknown"
    except:
        return "unknown"

def convert_units(bytes_value):
    """转换字节单位"""
    if UNITS == "MB":
        return bytes_value // (1024 * 1024)
    elif UNITS == "GB":
        return bytes_value // (1024 * 1024 * 1024)
    return bytes_value

def collect_mem_data():
    """采集内存使用数据"""
    mem = psutil.virtual_memory()
    return {
        "hostname": get_hostname(),
        "date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "used": convert_units(mem.used),
        "free": convert_units(mem.free),
        "total": convert_units(mem.total),
        "used_percent": f"{mem.percent:.2f}%"
    }

def send_data():
    """发送数据到服务端"""
    try:
        response = requests.post(
            API_URL,
            json=collect_mem_data(),
            timeout=TIMEOUT
        )
        if response.status_code == 200:
            print("内存数据提交成功")
            return True
        print(f"提交失败，状态码：{response.status_code}")
        return False
    except requests.exceptions.RequestException as e:
        print(f"请求失败：{str(e)}")
        return False

if __name__ == '__main__':
    send_data()
